import axios from "axios";

function blockExecution(ms: number) {
  const start = Date.now();
  while (Date.now() - start < ms) {
      // 空循环，阻塞执行
  }
}

const process = {
  env: {
    BOT_ID: "7408855137789902888",
    USER_ID: "teapot",
    BOT_TOKEN:
      "pat_WRM63o65BcplVXJdoy1QUAaihNEO5Le9l3q38FWSMlOXvzRetUWK01KYhLYRZXxb",
    CHAT_API: "https://api.coze.cn/v3/chat",
    GET_CHAT_API: "https://api.coze.cn/v3/chat/retrieve",
    GET_CHAT_MESSAGE_API: "https://api.coze.cn/v3/chat/message/list",
  },
};

const headers = {
  Authorization: `Bearer ${process.env.BOT_TOKEN}`,
  "Content-Type": "application/json",
};

//定义全局变量，用于获取参数
// 发起对话
const chat = async (content: string) => {
  const message = {
    bot_id: process.env.BOT_ID,
    user_id: process.env.USER_ID,
    additional_messages: [
      {
        role: "user",
        content: content,
        content_type: "text",
      },
    ],
  };

  const {data: { data },} = await axios.post(
      process.env.CHAT_API, //请求地址
      message, //body参数
      {
        // 配置请求头
        headers: headers,
      }
    )
    .then((res: any) => {
      return res;
    });

  return checkChatStatus(data);
};

// 查看对话详情
const getChat = async (chatData: any) => {
  blockExecution(1000); //能够阻塞函数执行
  // 发送 GET 请求
  const {data: { data } } = await axios.get(process.env.GET_CHAT_API, {
    params: {
      conversation_id: chatData.conversation_id,
      chat_id: chatData.id,
    },
    headers: headers,
  });
  if (data.status !== "completed") {
    return getChat(chatData);
  }

  if (data.status === "completed") {
    return getChatMessage(data);
  }
};

// 异步函数，轮询检查聊天状态
const checkChatStatus = async (chatData: any) => {
  // 轮询模式
  while (true) {
    // 发送 GET 请求
    const response = await axios.get(process.env.GET_CHAT_API, {
      params: {
        conversation_id: chatData.conversation_id,
        chat_id: chatData.id,
      },
      headers: headers,
    });
    const { data } = response.data;
    if (data.status === "completed") {
      // 状态完成，获取聊天消息并返回
      return getChatMessage(data);
    }
    // 状态未完成，等待一段时间后再次检查
    await new Promise((resolve) => setTimeout(resolve, 2000)); // 等待2秒
  }
};

// 查看对话消息详情
const getChatMessage = async (chatData: any) => {
  // 发送 GET 请求
  const {data: { data }} = await axios.get(process.env.GET_CHAT_MESSAGE_API, {
    params: {
      conversation_id: chatData.conversation_id,
      chat_id: chatData.id,
    },
    headers: headers,
  });
  return data[0].content;
};

export default chat